/**
 * @(#)SimulatorMonitorTask.java 2017年02月10日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */

package org.jsbd.boss.task;

import org.jsbd.boss.service.IEmailSendService;
import org.jsbd.boss.service.IMonitorConfigService;
import org.jsbd.boss.service.IMonitorFlagService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jsbd.boss.dao.ISimulatorActionStatisticsDao;
import org.jsbd.boss.domian.MonitorConfigBean;
import org.jsbd.boss.domian.monitor.MonitorFlagBean;
import org.jsbd.boss.domian.monitor.SimulatorActionStatistics;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 模拟器行为数据监控
 * @author Administrator
 *
 */
public class SimulatorMonitorTask extends BaseTask {

	public static final Logger LOGGER = LoggerFactory.getLogger(SimulatorMonitorTask.class);

	@Autowired
	private IEmailSendService emailSendService;
	
	public static final String KEY="simulator_action";
	
	private long currentId=0;
	
	@Autowired
	private ISimulatorActionStatisticsDao simulatorActionStatisticsDao;
	@Autowired
	private IMonitorConfigService monitorConfigService;
	@Autowired
	private IMonitorFlagService monitorFlagService;
	
	
	public void init() {
		super.setOpenFlag(PropertiesUtil.getValue("simulator_monitor_open_flag", "off"));
		super.setCycleTime(PropertiesUtil.getInt("simulator_monitor_time", 5000));
		super.init();
	}

	@Override
	public void run() {
		
		currentId=getCurrentId();
		
		while (true) {
			try {
				LOGGER.info("模拟器行为 监控");
				
				List<SimulatorActionStatistics> simulatorInfoList=simulatorActionStatisticsDao.getSimulatorActionStatisticsDao(currentId);
				if(simulatorInfoList==null||simulatorInfoList.isEmpty()){
					continue;
				}
				
            	doHandler(simulatorInfoList);
                
			} catch (Exception e) {
				LOGGER.error("", e);
			} finally {
				try {
					Thread.sleep(super.getCycleTime());
				} catch (InterruptedException e) {
					LOGGER.error("", e);
				}
			}
		}

	}
	
	private void doHandler(List<SimulatorActionStatistics> simulatorInfoList){
		Map<String, MonitorFlagBean> monitorFlagMap=monitorFlagService.getMonitorFlagMap(1);
        
		List<MonitorFlagBean>  mointorFlagList=new ArrayList<MonitorFlagBean>();
		
		for(SimulatorActionStatistics simulationAction:simulatorInfoList){
			currentId=simulationAction.getIndexNum();
			long realCount=simulationAction.getActionCount();
			String actionKey=simulationAction.getActionKey();
			
			MonitorFlagBean monitorFlag=monitorFlagMap.get(actionKey);
			if(monitorFlag==null){
				continue;
			}
			
			compareDataNum(monitorFlag,realCount,mointorFlagList);
		}
		
		saveCurrentId();
		
		if(mointorFlagList.isEmpty()){
			return;
		}
		
		monitorFlagService.updateMonitorFlag(mointorFlagList);
		monitorFlagService.saveMonitorFlagLog(mointorFlagList);
		
		StringBuffer content=new StringBuffer();
		for(MonitorFlagBean bean:mointorFlagList){
			content.append(bean.getMsg());
			content.append("<br>");
		}
		
		try {
			emailSendService.sendEmailToSysAccount("模拟器行为监控", content.toString(), null);
		} catch (IOException e) {
			LOGGER.error("Any error msg that u want to write",e);
		}
	}

	private void compareDataNum(MonitorFlagBean monitorFlag,long realCount,
			List<MonitorFlagBean>  mointorFlagList){
		long num=monitorFlag.getDataNum();
		String operation=monitorFlag.getOperation();
		
		boolean isOk=false;
		if(">".equals(operation)){
		    if(num>realCount){
		    	isOk=true;
		    }	
		}
		
        if("<".equals(operation)){
        	if(num<realCount){
		    	isOk=true;
		    }
		}
        
        //如果状态相同，则不需要报警
        if(isOk==monitorFlag.isOk()){
        	return;
        }
        
        String msg=null;
        
        //假如状态回复了
        if(isOk){
        	monitorFlag.setFlag(MonitorFlagBean.OK);
        	msg=monitorFlag.getOkMsg().replace("{other_msg}", realCount+"");
        }else{
        	monitorFlag.setFlag(MonitorFlagBean.ERROR);
        	msg=monitorFlag.getErrorMsg().replace("{other_msg}", realCount+"");
        }
        
        monitorFlag.setMsg(msg);
        mointorFlagList.add(monitorFlag);
	}
	
	private long getCurrentId(){
		MonitorConfigBean monitorConfig=new MonitorConfigBean();
		monitorConfig.setItemKey(KEY);
		MonitorConfigBean  conifg=monitorConfigService.getMonitorConfig(monitorConfig);
		return Long.valueOf(conifg.getItemValue());
	}
	
	private void saveCurrentId(){
		MonitorConfigBean monitorConfig=new MonitorConfigBean();
		monitorConfig.setItemKey(KEY);
		monitorConfig.setItemValue(currentId+"");
		monitorConfigService.updateMonitorConfigItemValue(monitorConfig);
	}

	
}
